package cn.youyeku.zsxh.ui.activity.tabAct;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.os.Bundle;

import android.os.Message;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.youyeku.zsxh.R;
import cn.youyeku.zsxh.Utils.CircleImageView;
import cn.youyeku.zsxh.Utils.LogUtils;
import cn.youyeku.zsxh.adapter.RefreshFootAdapter;
import cn.youyeku.zsxh.api.XhApi;
import cn.youyeku.zsxh.app;
import cn.youyeku.zsxh.bean.Question_center;
import cn.youyeku.zsxh.bean.QuestionCmt;
import cn.youyeku.zsxh.ui.UIControl;
import cn.youyeku.zsxh.ui.activity.ABS.AbsSwipeActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by youye on 17-4-3.
 */

public class ActGoodsExchange extends AbsSwipeActivity<QuestionCmt> {

    @BindView(R.id.good_exchange_imageV_head)
    CircleImageView goodExchangeImageVHead;

    @BindView(R.id.good_exchange_textV_nickname)
    TextView goodExchangeTextVNickname;

    @BindView(R.id.good_exchange_textV_btn_py)
    Button goodExchangeTextVBtnPy;

    @BindView(R.id.good_exchange_imgV_pic)
    ImageView goodExchangeImgVPic;

    @BindView(R.id.good_exchange_textV_price)
    TextView good_exchange_textV_price;

    @BindView(R.id.good_exchange_textV_detail_text)
    TextView goodExchangeTextVDetailText;

    @BindView(R.id.good_exchange_textV_date)
    TextView goodExchangeTextVDate;

    private String shop_id;
    @BindView(R.id.head_lay)
    View head_lay;

    private float startX;
    private float endX;
    private float startY;
    private float endY;


    public ActGoodsExchange() {
        super(R.id.tab_act_goods_exchange_recycler, R.id.tab_act_goods_exchange_swipe);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.tab_act_goods_exchange);

        ButterKnife.bind(this);
        Question_center questioncenter = (Question_center) getIntent().getSerializableExtra("questioncenter");

        goodExchangeTextVDate.setText("时间："+ questioncenter.getShop_goods_time());
        goodExchangeTextVDetailText.setText("问题描述："+ questioncenter.getShop_content());
        goodExchangeTextVNickname.setText(questioncenter.getNick_name());
        good_exchange_textV_price.setText("标题："+ questioncenter.getShop_title());
        shop_id = questioncenter.getShop_id();
        Glide.with(getApplicationContext())
                .load(XhApi.getFace(questioncenter.getShop_author_id()))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .error(R.drawable.default_avatar)
                .into(goodExchangeImageVHead);
        Glide.with(getApplicationContext())
                .load(XhApi.getShop(questioncenter.getShop_author_id(), questioncenter.getShop_pic()))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(goodExchangeImgVPic);

        super.onCreate(savedInstanceState);


    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        //在这里判断下滑还是上滑
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = ev.getX();
                startY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                endX = ev.getX();
                endY = ev.getY();
                break;
            case MotionEvent.ACTION_UP:

                if (endY - startY > 0 && (Math.abs(endY - startY) > 5*100)) {
                    //向下滑動
                    showToolBar();
                } else if (endY - startY < 0 && (Math.abs(endY - startY) > 4*100)) {
                    //向上滑动
                    hideToolBar();
                }
                startX = startY = endX = endY = 0;

                break;
        }
        return super.dispatchTouchEvent(ev);//不消费触摸事件
    }

    //隐藏动画 http://www.jianshu.com/p/e99b5e8bd67b?ref=myread 分发事件
    private void hideToolBar() {
        Animator animator = ObjectAnimator.ofFloat(head_lay, "translationY",
                head_lay.getTranslationY(), -head_lay.getHeight());
        animator.setDuration(600);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.setTarget(head_lay);
        animator.start();
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                head_lay.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    //显示动画
    private void showToolBar() {
        Animator animator = ObjectAnimator.ofFloat(head_lay, "translationY",
                head_lay.getTranslationY(), 0);
        animator.setDuration(600);
        animator.setInterpolator(new AccelerateInterpolator());
        animator.setTarget(head_lay);
        animator.start();
        head_lay.setVisibility(View.VISIBLE);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "评论")
                .setEnabled(true)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);


        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case Menu.FIRST:
                postComment();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void postComment() {
        new MaterialDialog.Builder(this)
                .title("提交评论")
                .inputType(InputType.TYPE_CLASS_TEXT)
                //参数1：hint 参数2：自动填充的文字 参数3：监听
                .input(null, null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        LogUtils.w(input.toString());
                        XhApi.post_comment(input.toString(), shop_id, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {

                                String data = response.body().string();
                                try {
                                    JSONObject object = new JSONObject(data);
                                    app.backgroundThreadShortToast(object.getString("message"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });
                    }
                }).show();

    }

    @Override
    protected RefreshFootAdapter<QuestionCmt> getAapter() {
        return new RefreshFootAdapter<QuestionCmt>(R.layout.cmt_item, R.layout.refresh_footer) {

            @Override
            protected void onBindCustomerData(RefreshViewHolder holder, QuestionCmt data, int pos) {
                ImageView face = holder.getChildView(R.id.cmt_face);
                TextView date = holder.getChildView(R.id.cmt_date);
                TextView content = holder.getChildView(R.id.cmt_content);
                TextView nick_name = holder.getChildView(R.id.cmt_nickname);
                Glide.with(getApplicationContext())
                        .load(XhApi.getFace(data.getUid()))
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .error(R.drawable.default_avatar)
                        .into(face);
                date.setText(data.getDatetime());

                content.setText(data.getCmt_text());
                nick_name.setText(data.getNick_name());
            }

            @Override
            protected void setmOnItemClick(View itemView, final QuestionCmt data, int pos) {
 itemView.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         UIControl.showUserInfo(getApplicationContext(), data.getUid());
     }
 });
            }
        };
    }

    @Override
    protected void requestData() {


        XhApi.get_shop_cmt(shop_id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                try {

                    JSONObject object = new JSONObject(data);
                    int code = object.getInt("code");
                    Gson gson = new Gson();
                    mData = gson.fromJson(object.getString("data"), new TypeToken<List<QuestionCmt>>() {
                    }.getType());
                    Message msg = new Message();
                    msg.what = code;

                    handler.sendMessage(msg);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
